<template>
  <view class="share_layout_box">
    <canvas class="myCanvas test" :style="'width:'+myCanvasWidth+'px;height:'+myCanvasHeight+'px'" canvas-id="shareFrendsId"></canvas>
  </view>
</template>
<script>
import canvasUtils from './canvasUtils'
export default {
  data () {
    return {
      myCanvasWidth: 240,
      myCanvasHeight: 192,
      dpiMun: 3,
    }
  },
  created () {
    this.myCanvasWidth = this.myCanvasWidth*this.dpiMun
    this.myCanvasHeight = this.myCanvasHeight*this.dpiMun
  },
  methods: {
    async shareFrends (data, from) {
      // wx.showLoading({
      //   title: '生成中...',
      //   mask: true
      // })
      const _this = this
      await _this.createdCode(data)
      let from_ = from
      // console.log(data, 1212)
      let shareData = {}
      wx.canvasToTempFilePath({
        canvasId: 'shareFrendsId',
        fileType: 'jpg',
        width: _this.myCanvasWidth,
        height: _this.myCanvasHeight,
        destWidth: _this.myCanvasWidth * 2,
        destHeight: _this.myCanvasHeight * 2,
        success: async (res) => {
          shareData = {
            code: '200',
            msg: '绘制成功！',
            type: data.type,
            shareType: data.type,
            url: res.tempFilePath,
          }
          if (from_ && from_.id) { // 链接需要带的参数
            shareData = {
              ...shareData,
              isPopup: from_.isPopup,
              dynamicId: from_.id
            }
          }
          _this.$store.commit('OPEN_GROUP_SHARE_DATA', shareData)
          if (shareData.code == 200) {
            _this.$emit('shareSuccess', shareData)
          }
          console.log(shareData,'绘制成功', from_)
          // wx.hideLoading()
        },
        fail: function (res) {
          console.log(res,'绘制失败')
          // wx.hideLoading()
        }
      },_this)
    },
    // 开始绘图
    createdCode (data) {
      const _this = this
      let fromData = data
      return new Promise(resolve => {
        exec()
        async function exec () {
          const ctx = wx.createCanvasContext('shareFrendsId', _this) // 绘图上下文
          ctx.setFillStyle('#ffffff')
          ctx.fillRect(0, 0, _this.myCanvasWidth, _this.myCanvasHeight)
          ctx.save()
          _this.handleBorderRect(ctx, 0, 0, _this.myCanvasWidth, _this.myCanvasHeight, 4*_this.dpiMun,'#ffffff')
          ctx.clip()
          if (fromData.bgImgUrl) {
            let bgImgUrl = fromData.bgImgUrl
            bgImgUrl = bgImgUrl+`?x-oss-process=image/resize,h_${_this.myCanvasHeight},w_${_this.myCanvasWidth},m_fill/auto-orient,1/quality,q_90/format,jpg`
            await canvasUtils.drawCoverImage(bgImgUrl, ctx, 0, 0, _this.myCanvasWidth, _this.myCanvasHeight)
            // 动态视频绘制播放按钮
            if (!fromData.isGoods) {
              await _this.drawImg('https://image.qqpyyds.com/mpAppImg/icon/play3_icon.png', ctx, _this.myCanvasWidth/2-(22*_this.dpiMun), _this.myCanvasHeight/2-(22*_this.dpiMun), 44*_this.dpiMun, 44*_this.dpiMun)
            }
          }

          await _this.drawImg('https://qqposs.oss-cn-shenzhen.aliyuncs.com/mpAppImg/other/share_name_bg.png', ctx, 0, 0, _this.myCanvasWidth, 40*_this.dpiMun)

          ctx.restore()
          ctx.save()
          ctx.beginPath()
          ctx.strokeStyle = '#fff'
          ctx.arc(16*_this.dpiMun,16*_this.dpiMun,10*_this.dpiMun,0,2*Math.PI)
          ctx.fill()
          ctx.clip()

          await _this.drawImg(fromData.userAvatar + '?x-oss-process=image/resize,w_64,h_64/auto-orient,1/quality,q_70/format,jpg', ctx, 6*_this.dpiMun, 6*_this.dpiMun, 20*_this.dpiMun, 20*_this.dpiMun)
          ctx.restore()
          ctx.setFontSize(10*_this.dpiMun)
          ctx.setFillStyle('#ffffff')
          ctx.fillText(fromData.userNickname, 30*_this.dpiMun, 20*_this.dpiMun, 100*_this.dpiMun)
          // 动态分享type==0，不显示人团人数
          if (fromData.type != 0) {
            // 一大波人赶来中
            let followGroup = fromData.followGroupNumber || '一大波人赶来中'
            await _this.drawImg('https://qqposs.oss-cn-shenzhen.aliyuncs.com/mpAppImg/other/heat_icon.png', ctx, _this.myCanvasWidth-ctx.measureText(followGroup).width-(22*_this.dpiMun), 9*_this.dpiMun, 12*_this.dpiMun, 12*_this.dpiMun)
            ctx.setFontSize(10*_this.dpiMun)
            ctx.setFillStyle('#ffffff')
            ctx.fillText(followGroup, _this.myCanvasWidth-ctx.measureText(followGroup).width-(8*_this.dpiMun), 20*_this.dpiMun, 160*_this.dpiMun)
          }
          if (fromData.type == 1) {
            // 为了计算字体长度ctx.measureText的默认是10个px字体
            let unit = '￥'
            ctx.setFontSize(16*_this.dpiMun)
            ctx.setFillStyle('#ffffff')
            ctx.fillText(fromData.salePrice, -10, -10)
            ctx.setFontSize(12*_this.dpiMun)
            ctx.setFillStyle('#ffffff')
            ctx.fillText(unit, -10, -10)
            ctx.setFontSize(16*_this.dpiMun)
            ctx.setFillStyle('#ffffff')
            ctx.fillText(fromData.btnText, -10, -10)
            // 为了计算字体长度END
            let btnTextW = ctx.measureText(fromData.btnText+'').width
            let salePriceW = ctx.measureText(fromData.salePrice+'').width
            let unitW = ctx.measureText(unit+'').width
            let widthMun = btnTextW + salePriceW + unitW + (37*_this.dpiMun)
            let leftw = (_this.myCanvasWidth-widthMun)/2
            await _this.drawImg('https://qqposs.oss-cn-shenzhen.aliyuncs.com/mpAppImg/other/salePrice_bg.png', ctx, leftw, 142*_this.dpiMun, widthMun, 40*_this.dpiMun)
            if (fromData.salePrice) {
              ctx.setFontSize(16*_this.dpiMun)
              ctx.setFillStyle('#ffffff')
              ctx.fillText(fromData.btnText, leftw+(18*_this.dpiMun), 168*_this.dpiMun)
              ctx.setFontSize(12*_this.dpiMun)
              ctx.setFillStyle('#ffffff')
              ctx.fillText(unit, leftw+btnTextW+(23*_this.dpiMun), 168*_this.dpiMun)
              ctx.setFontSize(16*_this.dpiMun)
              ctx.setFillStyle('#ffffff')
              ctx.fillText(fromData.salePrice, leftw+btnTextW+unitW+(18*_this.dpiMun), 168*_this.dpiMun)
            }
          }
          if (fromData.type == 2) {
            // 跟团按钮
            if (fromData.btnText.indexOf('跟团') !== -1) {
              await _this.drawImg('https://qqposs.oss-cn-shenzhen.aliyuncs.com/mpAppImg/other/share_name_bg1.png', ctx, _this.myCanvasWidth/2-(52*_this.dpiMun), 142*_this.dpiMun, 104*_this.dpiMun, 40*_this.dpiMun)
              ctx.setFontSize(16*_this.dpiMun)
              ctx.setFillStyle('#ffffff')
            } else {
              // 帮卖按钮--金色背景
              await _this.drawImg('https://qqposs.oss-cn-shenzhen.aliyuncs.com/mpAppImg/other/gold-btn-bg.png', ctx, _this.myCanvasWidth/2-(52*_this.dpiMun), 137*_this.dpiMun, 104*_this.dpiMun, 52*_this.dpiMun)
              ctx.setFontSize(14*_this.dpiMun)
              ctx.setFillStyle('#D85E0A')
            }
            ctx.fillText(fromData.btnText, (_this.myCanvasWidth-ctx.measureText(fromData.btnText).width)/2, 168*_this.dpiMun)
          }
          ctx.restore()
          ctx.draw(false, () => {
            resolve()
          })
        }
      })
    },
    // 画4个圆角
    handleBorderRect (ctx, x, y, w, h, r, color) {
      ctx.beginPath()
      // 左上角
      ctx.arc(x + r, y + r, r, Math.PI, 1.5 * Math.PI)
      ctx.moveTo(x + r, y)
      ctx.lineTo(x + w - r, y)
      ctx.lineTo(x + w, y + r)
      // 右上角
      ctx.arc(x + w - r, y + r, r, 1.5 * Math.PI, 2 * Math.PI)
      ctx.lineTo(x + w, y + h - r)
      ctx.lineTo(x + w - r, y + h)
      // 右下角
      ctx.arc(x + w - r, y + h - r, r, 0, 0.5 * Math.PI);
      ctx.lineTo(x + r, y + h)
      ctx.lineTo(x, y + h - r)
      // 左下角
      ctx.arc(x + r, y + h - r, r, 0.5 * Math.PI, Math.PI)
      ctx.lineTo(x, y + r)
      ctx.lineTo(x + r, y)
      ctx.fillStyle = color
      ctx.fill()
      ctx.closePath()
    },
    // 文字自动换行
    wordsWrap (ctx, name, nameWidth, maxWidth, startX, srartY, wordsHight) {
      let lineWidth = 0
      let lastSubStrIndex = 0
      for (let i = 0; i < name.length; i++) {
        lineWidth += ctx.measureText(name[i]).width
        if (lineWidth > maxWidth) {
          ctx.fillText(name.substring(lastSubStrIndex, i), startX, srartY)
          srartY += wordsHight
          lineWidth = 0
          lastSubStrIndex = i
        }
        if (i === name.length - 1) {
          ctx.fillText(name.substring(lastSubStrIndex, i + 1), startX, srartY)
        }
      }
    },
    // 绘制远程网络图片
    async drawImg (url, ctx, startX, startY, width, height) {
      let _this = this
      return new Promise(resolve => {
        exec()
        async function exec () {
          wx.getImageInfo({
            src: url,
            success: function (res) {
              const filePath = res.path
              ctx.drawImage(filePath, startX, startY, width, height)
              resolve()
            },
          })
        }
      })
    },
  },
}
</script>
<style scoped lang="scss">
.share_layout_box {
  position: fixed;
  left: -1000px;
  top: -1000px;
  // z-index: 999;
}
</style>
